package pers.llc.css.excutor;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author lls
 */
public class PrimeGenerator implements Runnable {

    private final List<BigInteger> primes = new ArrayList<>();

    /**
     * 保证变量的可见性
     */
    private volatile boolean cancelled;

    @Override
    public void run() {
        BigInteger p = BigInteger.ONE;
        while (!cancelled) {
            //大于此BigIntegr的第一个素数
            p = p.nextProbablePrime();
            synchronized (this) {
                System.out.println("素数：" + p);
                primes.add(p);
                System.out.println(primes.size() + "......");
            }
        }
    }

    public void canael() {
        cancelled = true;
    }

    public synchronized List<BigInteger> get() {
        return new ArrayList<BigInteger>(primes);
    }

    public static void main(String[] args) throws InterruptedException {
        PrimeGenerator generator = new PrimeGenerator();
        new Thread(generator).start();
        try {
            //休眠期时间即是产生素数的时间
            TimeUnit.MILLISECONDS.sleep(10);
        } finally {
            generator.canael();
        }
        //get完成后，add再次拿到锁再次添加了一个素数，但get方法却已经执行了，所以size会比实际的少1或更少
        List<BigInteger> list = generator.get();
        for (BigInteger i : list) {
            System.out.println(i);
        }
    }

}
